package com.douban.crawl.servlet;

import com.douban.crawl.db.UserDao;
import com.douban.crawl.model.SysUser;
import com.douban.crawl.utils.DateUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;


public class RegisterServlet extends HttpServlet {

    private UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        SysUser sysUser = userDao.getUser(username);
        if (sysUser != null) {
            // 用户已存在
            req.setAttribute("error_info", "该用户已存在，请去登录");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        } else {
            SysUser dbSysUser = new SysUser(username, password, email, DateUtils.dateToStr(new Date()));
            userDao.save(dbSysUser);
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }
}
